﻿using System;
using System.Xml.Serialization;

namespace Altairis.OtpAuth.Core {
    [XmlRoot(ElementName = "eventOtpToken", Namespace = XmlNs.SERIALIZATION_NS_URL)]
    public class EventOtpToken : OtpToken {

        // Constructors

        public EventOtpToken()
            : base() {
            this.Generator = new EventOtpGenerator();
        }

        // Properties

        private long _counter;

        [XmlAttribute("counter")]
        public long Counter {
            get { return _counter; }
            set {
                if (value < 0) throw new ArgumentOutOfRangeException("Counter cannot be set to negative value.");
                _counter = value;
            }
        }

        [XmlElement("generator")]
        public EventOtpGenerator Generator { get; set; }

        // Methods

        public override string GenerateCurrentOneTimePassword() {
            if (this.Generator == null) throw new InvalidOperationException("Cannot generate OTP when Generator property is null.");
            if (this.Secret == null || this.Secret.Length == 0) throw new InvalidOperationException("Cannot generate OTP when Secret property is null or empty.");

            var otp = this.Generator.GenerateOneTimePassword(this.Secret, this.Counter);
            this.Counter++;
            return otp;
        }

    }
}
